package com.nifostasky.comic.business.controller;

import com.nifostasky.comic.common.utils.URLUtils;
import io.swagger.annotations.*;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.server.ServletServerHttpResponse;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * 代理
 */
@RestController
@RequestMapping("/agentController")
@Api(tags = "代理")
@Slf4j
@ApiSort(9999)
@AllArgsConstructor
public class AgentController {

    @ApiOperation("图片代理(解决防盗链问题)")
    @GetMapping("/forwardPicture")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "url", value = "图片url地址", dataType = "Int", required = true),
            @ApiImplicitParam(name = "referer", value = "源", dataType = "Int", required = true)
    })
    @ApiOperationSupport(order = 1)
    @SneakyThrows
    public void forwardPicture(String url,String referer , HttpServletResponse response){
        ByteArrayResource resource = null;
        InputStream inputStream;
        try {
            Map<String, Object> header = new HashMap<>();
            header.put("Referer", referer);
            inputStream = URLUtils.httpInputGet(url, header);
            resource = new ByteArrayResource(toByteArray(inputStream));
        } catch (Exception e) {
            e.printStackTrace();
        }
        response.setHeader("content-type", "application/octet-stream");
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "inline;filename=" + URLEncoder.encode(url, "UTF-8"));
        byte[] buffer = new byte[1024];
        OutputStream outputStream = response.getOutputStream();
        InputStream fis = resource.getInputStream();
        BufferedInputStream bis = null;
        bis = new BufferedInputStream(fis);
        int i = bis.read(buffer);
        while (i != -1) {
            outputStream.write(buffer, 0, i);
            i = bis.read(buffer);
        }
    }

    private byte[] toByteArray(InputStream in){
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        try {
            byte[] bytes = new byte[1024];
            int n;
            while ((n = in.read(bytes)) != -1){
                byteArrayOutputStream.write(bytes, 0, n);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return byteArrayOutputStream.toByteArray();
    }

}
